class Compiler {
  constructor(vm) {
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }
  compile(el) {
    let childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      // 处理文本节点
      if (this.isTextNode(node)) {
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        // 处理元素节点
        this.compileElement(node)
      }
      if (node.childNodes && node.childNodes.length > 0) {
        this.compile(node)
      }
    })
  }
  compileElement(node) {
    let attrs = node.attributes
    Array.from(attrs).forEach(attr => {
      let attrName = attr.name
      let attrValue = attr.value
      if (this.isDirective(attrName)) {
        attrName = attrName.slice(2)
        this.update(node, attrName, this.vm[attrValue], attrValue)
      }
    })
  }
  update(node, attrName, value, key) {
    let updateFn = this[attrName + 'Update']
    updateFn && updateFn.call(this, node, value, key)
  }
  textUpdate(node, value, key) {
    node.textContent = value
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }
  modelUpdate(node, value, key) {
    node.value = value
    new Watcher(this.vm, key, newValue => {
      node.value = newValue
    })
    node.addEventListener('input', (value) => {
      this.vm[key] = node.value
    })
  }
  /**
   * @description 
   * @author liuxiangwei
   * @date 2025-58-21 10:08:29
   * @param {*} node
   */
  compileText(node) {
    let text = node.textContent
    let reg = /\{\{(.+?)\}\}/
    if (reg.test(text)) {
      const key = RegExp.$1.trim()
      node.textContent = text.replace(reg, this.vm[key])
      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue
      })
    }
  }
  /**
   * 判断给定元素属性是否是自定义指令
   * @description 
   * @author liuxiangwei
   * @date 2025-17-21 10:08:22
   * @param {string} attrName 元素属性名称
   * @returns {boolean} 是否是自定义指令
   */
  isDirective(attrName) {
    return attrName.startsWith('v-')
  }
  /**
   * 判断给定元素节点是否是文本节点
   * @author liuxiangwei
   * @date 21/08/2025
   * @param {*} node 元素节点
   * @returns {boolean} 返回是否是文本节点
   */
  isTextNode(node) {
    return node.nodeType === 3
  }
  /**
   * 判断给定节点是否是元素节点
   * @author liuxiangwei
   * @date 21/08/2025
   * @param {*} node 元素节点
   * @return {boolean} 返回是否是元素节点
   */
  isElementNode(node) {
    return node.nodeType === 1
  }
}